package com.ty.proxy;

import com.ty.annotation.RequirePermission;
import com.ty.utils.PermissionUtils;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class PermissionProxy implements InvocationHandler {
    private Object target;
    private HttpServletRequest request;

    public PermissionProxy(Object target, HttpServletRequest request) {
        this.target = target;
        this.request = request;
    }

    public static Object newInstance(Object target, HttpServletRequest request) {
        return Proxy.newProxyInstance(
                target.getClass().getClassLoader(),
                target.getClass().getInterfaces(),
                new PermissionProxy(target, request)
        );
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        RequirePermission requirePermission = method.getAnnotation(RequirePermission.class);
        if (requirePermission != null) {
            if (!PermissionUtils.hasAdminPermission(request)) {
                throw new SecurityException("没有权限进行此操作");
            }
        }
        return method.invoke(target, args);
    }
}